"""
序列化器定义
用于API数据的序列化和反序列化
"""
from rest_framework import serializers
from django.contrib.auth.hashers import make_password
from .models import User, Category, Novel, Chapter, Bookshelf, AuthorApplication


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    password = serializers.CharField(write_only=True, required=False)  # 密码只写不读

    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'password', 'role', 'avatar', 'bio', 'date_joined']
        read_only_fields = ['role', 'date_joined']  # 角色和注册日期是只读的

    def create(self, validated_data):
        """创建用户时对密码进行哈希处理"""
        validated_data['password'] = make_password(validated_data.get('password'))
        return super().create(validated_data)

    def update(self, instance, validated_data):
        """更新用户时对密码进行哈希处理"""
        if 'password' in validated_data:
            validated_data['password'] = make_password(validated_data.get('password'))
        return super().update(instance, validated_data)


class CategorySerializer(serializers.ModelSerializer):
    """分类序列化器"""

    class Meta:
        model = Category
        fields = ['id', 'name', 'created_at']
        read_only_fields = ['created_at']


class ChapterSerializer(serializers.ModelSerializer):
    """章节序列化器"""
    novel_title = serializers.ReadOnlyField(source='novel.title')  # 小说标题只读

    class Meta:
        model = Chapter
        fields = ['id', 'novel', 'novel_title', 'title', 'content', 'order', 'created_at', 'updated_at']
        read_only_fields = ['created_at', 'updated_at']


class NovelSerializer(serializers.ModelSerializer):
    """小说序列化器"""
    author_name = serializers.ReadOnlyField(source='author.username')  # 作者名只读
    category_name = serializers.ReadOnlyField(source='category.name')  # 分类名只读

    class Meta:
        model = Novel
        fields = ['id', 'title', 'author', 'author_name', 'category', 'category_name',
                  'cover', 'description', 'status', 'created_at', 'updated_at']
        read_only_fields = ['author', 'status', 'created_at', 'updated_at']


class NovelDetailSerializer(NovelSerializer):
    """带有章节信息的小说详情序列化器"""
    chapters = serializers.SerializerMethodField()  # 自定义方法获取章节

    class Meta(NovelSerializer.Meta):
        fields = NovelSerializer.Meta.fields + ['chapters']

    def get_chapters(self, obj):
        """获取小说的所有章节"""
        chapters = obj.chapters.all().order_by('order')
        return ChapterSerializer(chapters, many=True).data


class BookshelfSerializer(serializers.ModelSerializer):
    """书架序列化器"""
    novel_detail = NovelSerializer(source='novel', read_only=True)  # 包含完整的小说信息
    last_read_chapter_title = serializers.ReadOnlyField(source='last_read_chapter.title', default=None)  # 最后阅读章节标题

    class Meta:
        model = Bookshelf
        fields = ['id', 'user', 'novel', 'novel_detail', 'last_read_chapter', 'last_read_chapter_title', 'added_at']
        read_only_fields = ['user', 'added_at']


class AuthorApplicationSerializer(serializers.ModelSerializer):
    """作者申请序列化器"""
    user_detail = UserSerializer(source='user', read_only=True)  # 包含完整的用户信息

    class Meta:
        model = AuthorApplication
        fields = ['id', 'user', 'user_detail', 'reason', 'status', 'created_at', 'processed_at', 'admin_notes']
        read_only_fields = ['created_at', 'processed_at', 'status', 'admin_notes']


class LoginSerializer(serializers.Serializer):
    """登录序列化器"""
    username = serializers.CharField(required=True)
    password = serializers.CharField(required=True, write_only=True)


# 用于创建新小说的序列化器
class NovelCreateSerializer(serializers.ModelSerializer):
    # 在这个类中，我们定义了如何序列化 `Novel` 模型的字段
    class Meta:
        model = Novel  # 指定与之关联的模型是 Novel
        fields = ['title', 'category', 'cover', 'description']  # 序列化时需要的字段
        extra_kwargs = {
            # 设置 `description` 字段为必填项
            'description': {'required': True}
        }

    def create(self, validated_data):
        # 自动关联当前用户为作者
        validated_data['author'] = self.context['request'].user
        return super().create(validated_data)

    # 该序列化器用于处理创建小说时的字段验证和数据转换，特别是：
    # 1. `title`: 小说标题
    # 2. `category`: 小说的类别
    # 3. `cover`: 小说封面
    # 4. `description`: 小说描述，必须提供（由于 `required=True`）


# 用于更新小说状态的序列化器
class NovelStatusSerializer(serializers.ModelSerializer):
    # 这个序列化器用于处理小说状态字段的读取，通常用于只读场景
    class Meta:
        model = Novel  # 同样关联到 Novel 模型
        fields = ['status']  # 只包括小说的状态字段
        read_only_fields = ['status']  # 将 `status` 字段设置为只读，不允许修改

    # 这个序列化器主要用于显示小说的当前状态，而不允许用户修改它。
    # `status` 字段可能用于跟踪小说的发布状态、连载情况等，并且不允许客户端在此过程中更改它。


class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ['id', 'name']
